#pragma once

#include <iostream>
#include <queue>
using namespace std;
#include <pthread.h>
#include <ctime>
#include <unistd.h>



int g_cap = 5; // 队列容量

template<class T>
class blockQueue
{
public:
    blockQueue(size_t cap=g_cap)
    :_cap(cap)
    ,_name(nullptr)
    {
        //初始化锁和条件变量
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_producerCond,nullptr);
        pthread_cond_init(&_customerCond,nullptr);
    }
    ~blockQueue()
    {
        //销毁锁和条件变量
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_producerCond);
        pthread_cond_destroy(&_customerCond);

    }
    bool isFull()
    {
        return _q.size()==_cap;
    }
    bool isEmpty()
    {
        return _q.size()==0;
    }
    void push(const T& in)
    {
        //usleep(100);

        pthread_mutex_lock(&_mutex);

        while(isFull())
        {
            pthread_cond_wait(&_producerCond,&_mutex);

        }
        _q.push(in);
        pthread_cond_signal(&_customerCond);

        pthread_mutex_unlock(&_mutex);

    }
    void pop(T& out)
    {
        sleep(1);

        pthread_mutex_lock(&_mutex);
        while(isEmpty())
        {
            pthread_cond_wait(&_customerCond,&_mutex);
        }
        out=_q.front();
        _q.pop();
        
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_producerCond);

    }
    // void Name(const char* name)
    // {
    //     _name=name;
    // }
    // const char* getName()
    // {
    //     return _name;
    // } 

private:
    queue<T> _q;
    size_t _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _producerCond;
    pthread_cond_t _customerCond;
    const char* _name;

};